package com.aixin.project.db;

import com.aixin.project.data.CourseOrder;
import com.aixin.project.data.Fee;
import com.aixin.project.util.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by IntelliJ IDEA.
 * User: Sufeng
 * Date: 12-4-15
 * Time: 下午10:41
 * To change this template use File | Settings | File Templates.
 */
public class FeeDao extends Dao {
    public static long create(Fee fee) {
        long ret = -1;
        try {
            DBUtil.startTransaction();
            Connection con = DBUtil.getContainer().get();
            QueryRunner run = new QueryRunner();
            int update = run.update(con, "insert into fee(type,orderid,userid,fee) values(?,?,?,?)",
                    fee.getType(), fee.getOrderid(), fee.getUserid(), fee.getFee());
            if (update > 0) {
                System.out.println("update value:"+update);
                long feeid = (Long) run.query(con, "SELECT LAST_INSERT_ID()", new ScalarHandler(1));
                update = run.update(con, "update courseorder set status=1 where id=?", fee.getOrderid());
                if (update > 0) {
                    System.out.println("commit...");
                    DBUtil.commit();
                    ret = feeid;
                } else {
                    System.out.println("rollback1....");
                    DBUtil.rollback();
                }
            }
        } catch (SQLException e) {
            System.out.println("rollback2...");
            DBUtil.rollback();
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return ret;
    }
}
